package com.hz.ruoyilgorder.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.hz.rouyigonggong.domain.*;
import com.hz.rouyigonggong.domain.basedomain.BaseDomain;
import com.hz.rouyigonggong.domain.dto.LgDeliveryInfoDTO;
import com.hz.rouyigonggong.domain.dto.LgDriverLogisticsDTO;
import com.hz.rouyigonggong.domain.dto.LgOutOrderDTO;
import com.hz.rouyigonggong.domain.dto.LgSellerOrderDTO;
import com.hz.ruoyilgorder.api.service.LgSellerInfoService;
import com.hz.ruoyilgorder.config.LgOutOrderConverter;
import com.hz.ruoyilgorder.config.LgSellerOrderConverter;
import com.hz.ruoyilgorder.mapper.LgDeliveryInfoDTOMapper;
import com.hz.ruoyilgorder.mapper.LgOutOrderDTOMapper;
import com.hz.ruoyilgorder.service.LgDeliveryInfoService;
import com.hz.ruoyilgorder.service.LgOutOrderService;
import com.hz.ruoyilgorder.utils.ResultJSON;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Author yzw
 * @Date 2025/3/8 18:11
 * @注释
 */
@RestController
@RequestMapping("/outorder")
public class LgOutOrderController {
    @Autowired
    private LgOutOrderService lgOutOrderService;
    @Autowired
    private LgDeliveryInfoService   lgDeliveryInfoService;
    @Autowired
    private LgDeliveryInfoDTOMapper lgDeliveryInfoDTOMapper;
    @Autowired
    private LgSellerInfoService lgSellerInfoService;
    @Autowired
    private LgOutOrderDTOMapper lgOutOrderDTOMapper;



    @GetMapping("/add")
    public AjaxResult add(LgOutOrder lgOutOrder){
        System.out.println(lgOutOrder+"******************");
        boolean save = lgOutOrderService.save(lgOutOrder);
        return AjaxResult.success(save);
    }
    @GetMapping("/getOutOrderById")
    public AjaxResult getOutOrderById(Integer id){
        return AjaxResult.success(lgOutOrderService.getOutOrderById(id));
    }
    @GetMapping("/getOutOrderBySellerId")
    public AjaxResult getOutOrderBySellerId(Integer sellerId){
        QueryWrapper<LgOutOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seller_id",sellerId);
        queryWrapper.orderByDesc("create_time");
        return AjaxResult.success(lgOutOrderService.list(queryWrapper));
    }

    @RequiresPermissions("outorder:every:list")
    @GetMapping("/getlist")
    public TableDataInfo getLgSellerOrderList(LgOutOrderDTO entity){
       // System.out.println(entity);
        startPage();
        entity.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        List<LgOutOrderDTO> list= lgOutOrderService.querylist(entity);
        return getDataTable(list);
    }

    //查询
    @RequiresPermissions("outorder:every:query")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable Integer id) {

        return AjaxResult.success(lgOutOrderService.getInfo(id));
    }
    //修改
    @RequiresPermissions("outorder:every:edit")
    @PostMapping("/edit")
    //@GlobalTransactional//分布式事务
    public AjaxResult edit(@Validated @RequestBody  LgOutOrderDTO orderDTO) {
        orderDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        LgOutOrder order = LgOutOrderConverter.toEntity(orderDTO);
            //当出库完成时 修改仓储信息表
            if (order.getOrderStatus()==8){
                LgOutOrderDTO info = lgOutOrderDTOMapper.getorder(order.getStockOrderNumber());
                System.out.println("------------------------"+info);
                LgSellerInfo lgSellerInfo = lgSellerInfoService.getSellerInfoIdBySellerIdAndGoodsId(info.getSellerId(), info.getGoodsId());
                lgSellerInfo.setRemainingWeight((int) info.getOutWeight().doubleValue());
                lgSellerInfo.setRemainingQuantity(info.getOutQuantity());
                lgSellerInfoService.updateSellerInfo(lgSellerInfo);
                order.setOutTime(new Timestamp(System.currentTimeMillis()));
            }
            if (order.getOrderStatus()==9){
                LgDeliveryInfo lgDeliveryInfo = new LgDeliveryInfo();
                lgDeliveryInfo.setOrderNumber(orderDTO.getStockOrderNumber());
                lgDeliveryInfo.setIsCompleted(2);
                Wrapper<LgDeliveryInfo> lgSellerOrderWrapper = new QueryWrapper<LgDeliveryInfo>()
                        .eq("order_number", orderDTO.getStockOrderNumber());
                lgDeliveryInfoService.update(lgDeliveryInfo, lgSellerOrderWrapper);
            }
        Wrapper<LgOutOrder> lgOutOrder = new QueryWrapper<LgOutOrder>()
                .eq("stock_order_number", orderDTO.getStockOrderNumber());

        return AjaxResult.success(lgOutOrderService.update(order,lgOutOrder));
    }
    @RequiresPermissions("outorder:every:add")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody  LgOutOrderDTO orderDTO) {
        orderDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        //转换
        LgOutOrder order = LgOutOrderConverter.toEntity(orderDTO);
        //测试默认设为1，到时候需要在uniapp获得 cookie
        order.setSellerId(1);
        return  AjaxResult.success(lgOutOrderService.save(order));
    }

    //指派司机
    @RequiresPermissions("order:every:driver")
    @PostMapping("/driver")
    public ResultJSON driver(@RequestBody Map<String, Object> body) {

        Integer orderNumber = (Integer) body.get("orderNumber");
        Integer driverId = (Integer) body.get("driverId");
        String buyerPhone = (String) body.get("buyerPhone");
        String buyerName = (String) body.get("buyerName");
        Integer coldId = (Integer) body.get("coldId");

        LgDeliveryInfoDTO lgDeliveryInfoDTO = new LgDeliveryInfoDTO();
        lgDeliveryInfoDTO.setOrderNumber(orderNumber);
        lgDeliveryInfoDTO.setDriverId(driverId);
        lgDeliveryInfoDTO.setBuyerPhone(buyerPhone);
        lgDeliveryInfoDTO.setBuyerName(buyerName);
        lgDeliveryInfoDTO.setColdId(coldId);
        lgDeliveryInfoDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        if(lgDeliveryInfoService.adddriver(lgDeliveryInfoDTO)>=1){
            LgOutOrder lgOutOrder = new LgOutOrder();
            lgOutOrder.setOrderStatus(6);
            lgOutOrder.setStockOrderNumber(orderNumber);
            Wrapper<LgOutOrder> lgSellerOrderWrapper = new QueryWrapper<LgOutOrder>()
                    .eq("stock_order_number", orderNumber);
            lgOutOrderService.update(lgOutOrder, lgSellerOrderWrapper);
            return  ResultJSON.success();
        }
        return  ResultJSON.error();

    }


    //指派车辆
    @RequiresPermissions("order:every:car")
    @PostMapping("/assignCar")
    public ResultJSON assignCar(@RequestBody Map<String, Object> body) {

        Integer orderNumber = (Integer) body.get("orderNumber");
        Integer carId = (Integer) body.get("carId");
        String buyerPhone = (String) body.get("buyerPhone");
        String buyerName = (String) body.get("buyerName");
        Integer coldId = (Integer) body.get("coldId");
        LgDeliveryInfoDTO lgDeliveryInfoDTO = new LgDeliveryInfoDTO();
        lgDeliveryInfoDTO.setOrderNumber(orderNumber);
       lgDeliveryInfoDTO.setVehicleId(carId);
//        if(lgDeliveryInfoDTOMapper.getorder(lgDeliveryInfoDTO.getOrderNumber()).getVehicleId()==null){
            lgDeliveryInfoDTO.setBuyerPhone(buyerPhone);
            lgDeliveryInfoDTO.setBuyerName(buyerName);
//        }
        lgDeliveryInfoDTO.setColdId(coldId);
        if(lgDeliveryInfoService.add(lgDeliveryInfoDTO)>=1){
            LgOutOrder lgOutOrder = new LgOutOrder();
            lgOutOrder.setOrderStatus(7);
            lgOutOrder.setStockOrderNumber(orderNumber);
            Wrapper<LgOutOrder> lgSellerOrderWrapper = new QueryWrapper<LgOutOrder>()
                    .eq("stock_order_number", orderNumber);
            lgOutOrderService.update(lgOutOrder, lgSellerOrderWrapper);
            return  ResultJSON.success();
        }

        return  ResultJSON.error();
    }



    protected void startPage()
    {
        PageUtils.startPage();
    }
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }




}
